<?php
/**
 * 单设备登录检查中间件
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\admin\middleware;

use app\admin\service\LoginDeviceService;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class OneDeviceLoginCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $check = (int)setting('admin.safe.one_device_login');
        if (!$check || !isset($request->user)) {
            return $handler($request);
        }

        $device_id = $request->device_id;

        $service = new LoginDeviceService($request->user);

        $login_device_id = $service->getLoginDeviceId();

        if ($login_device_id && $login_device_id !== $device_id) {

            $login_url = url('admin/auth/login');
            if ($request->method() === 'GET') {
                return redirect($login_url);
            }
            return admin_error('账号已在其他地方登录', $login_url);
        }

        return $handler($request);
    }
}
